<template>
  <div class="project-setting project-status-setting">
    <div class="setting-header">
      <div class="setting-title">
        {{ $t('projectManage.setting.projectStatus.title') }}
      </div>
      <div class="setting-action">
        <el-button type="primary" @click="addProjectStatus"><i class="el-icon-plus"></i> {{ $t('projectManage.setting.projectStatus.createStatus') }}</el-button>
      </div>
    </div>
    <div class="status-desc">{{ $t('projectManage.setting.projectStatus.tip1') }}</div>
    <div class="setting-content" v-loading="loading">
        <BaseListForNoData v-show="!loading && !tableData.length" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
        <!-- 工单备注 table -->
        <template v-if="tableData.length">
          <div class="status-draggable">
            <el-table
              v-table-style
              row-key="id"
              :data="tableData"
              header-row-class-name="common-list-table-header__v2"
              border>

              <el-table-column type="index" width="50">
                <template slot-scope="scope">
                  <span :class="scope.row.canDelete ? 'moveEle' : 'undraggable'"><i v-if="scope.row.canDelete" class="iconfont icon-tuozhuaipaixu" /></span>
                </template>
              </el-table-column>
              <el-table-column
                v-for="(column, index) in columns"
                :key="`${column.displayName}_${index}`"
                :prop="column.fieldName"
                :label="column.displayName"
                :min-width="column.minWidth || '108px'"
                show-overflow-tooltip
                >
                <template slot-scope="scope">
                  <template v-if="column.fieldName === 'projectStatusName'">
                    <div class="status-color">
                      <span :style="{backgroundColor: scope.row.statusColor || '#F6C659'}">{{ scope.row.projectStatusName }}</span> 
                    </div> 
                  </template>
                  <template v-else>
                    {{ $formatFormField(column, scope.row) }}
                  </template>
                </template>
              </el-table-column>
              <el-table-column fixed="right" :label="$t('common.base.table.col.operator')" width="180px">
                <template slot-scope="scope">
                  <template v-if="scope.row.canDelete">
                    <el-button size="small" type="text" @click="editRow(scope.row)">{{$t('common.base.edit')}}</el-button>
                    <el-button size="small" class="danger-btn" type="text" @click="deleteRow(scope.row)">{{$t('common.base.delete')}}</el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
    </div>
    <!-- 新建状态弹窗 -->
    <create-status ref="CreateStatusModal" @submitStatus="submitStatus" :statusList="tableData"></create-status>
  </div>
</template>
<script>
import NoDataView from '@src/component/common/NoDataViewNew';
import CreateStatus from '@src/modules/setting/projectManage/components/ProjectStatus/components/CreateStatus.vue'
import _,{ cloneDeep }  from 'lodash';
import * as ProjectManage from '@src/api/ProjectManage.ts';
import Sortable from 'sortablejs';

export default {
  name: 'project-status',
  data() {
    return  {
      tableData: [],
      loading: false,
    }
  },
  components: {
    NoDataView,
    CreateStatus
  },

  computed: {
    columns() {
      let columns = [
        {
          displayName: this.$t('projectManage.setting.projectStatus.statusName'),
          fieldName: 'projectStatusName',
          setting: {
            originalFormType: 'text',
          },
        },
        {
          displayName: this.$t('common.base.explain'),
          fieldName: 'projectStatusDesc',
          setting: {
            originalFormType: 'text',
          },
          minWidth: '260px',
        },
      ];
      return columns;
    },
  },
  props: {
    templateId: {
      type: String | Number,
      default: '',
    },
  },
  // 页面初始化
  mounted() {
    this.getStatusList()
  },
  methods: {
    // 行拖拽
    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.status-draggable .el-table__body-wrapper tbody');
      const _this = this;
      Sortable.create(tbody, {
          //指定父元素下可被拖拽的子元素
          handle:  '.moveEle',
          filter: '.undraggable',
          onEnd({newIndex, oldIndex}) {
            const currRow = _this.tableData.splice(oldIndex, 1)[0];
            _this.tableData.splice(newIndex, 0, currRow);
            _this.handleUpdateSort()
          }
      });
    },
    getStatusList() {
      this.loading = true
      ProjectManage.getStatusList({projectTypeId: this.templateId}).then((res) => {
        this.loading = false
        if (res.success) {
          this.$set(this, 'tableData', res.data || [])
          if (this.tableData.length) {
            this.$nextTick(() => {
              this.rowDrop()
            })
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 添加项目状态
    addProjectStatus() {
      this.$refs.CreateStatusModal.openDialog()
    },

    onMove(e) {
      let index = e.relatedContext.index
      if (index === 0 || index === (this.tableData.length - 1)) {
        return false
      }
      return true
    },
    // 更新排序
    handleUpdateSort() {
      let sortList = this.tableData.filter((item) => item.canDelete)
      sortList = sortList.map((item,index) => {
        return {
          id: item.id,
          orderNumber: (index + 2)
        }
      })
      let params = {
        updateOrderList: sortList,
        projectTypeId: this.templateId,
      }
      ProjectManage.statusSwap(params).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.getStatusList()
      })
    },

    submitStatus(form, isEdit,nameLanguage) {
      // 保证参数projectStatusName一直是中文
      form.projectStatusName = nameLanguage?.zh || form?.projectStatusName
      if (isEdit) {
        let params = {
          ...form,
          projectTypeId: this.templateId,
          nameLanguage
        }
        ProjectManage.statusUpdate(params).then((res) => {
          if(res.success) {
            this.$message.success(this.$t('common.base.tip.edit2Success'));
            this.$refs.CreateStatusModal.closeDialog()
            this.getStatusList()
          } else {
            this.$message.error(res.message || this.$t('common.base.tip.editFail'));
          }
        })
      } else {
        let params = {
          ...form,
          projectTypeId: this.templateId,
          nameLanguage
        }
        ProjectManage.statusAdd(params).then((res) => {
          if(res.success) {
            this.$message.success(this.$t('common.base.tip.createSuccess2'));
            this.$refs.CreateStatusModal.closeDialog()
            this.getStatusList()
          } else {
            this.$message.error(res.message || this.$t('common.base.tip.createError2'));
          }
        })
      }
    },
    editRow(item) {
      this.$refs.CreateStatusModal.openDialog(item, true)
    },
    deleteRow(item) {
      let params = {
        id: item.id,
        projectTypeId: this.templateId
      }
      ProjectManage.statusDelCheck({id: item.id, projectTypeId: this.templateId}).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        if (res.data.flag) {
          this.$confirm(this.$t('projectManage.setting.projectStatus.confirmMess1'), this.$t('common.base.delete'), {
            confirmButtonText: this.$t('common.base.makeSure'),
            cancelButtonText: this.$t('common.base.cancel'),
            type: 'warning',
          })
          .then(() => {
            this.confirmDelete(params)
          })
        } else {
          this.$confirm(this.$t('projectManage.setting.projectStatus.confirmMess2'), this.$t('common.base.delete'), {
            confirmButtonText: this.$t('common.base.makeSure'),
            cancelButtonText: this.$t('common.base.cancel'),
            type: 'warning',
          })
          .then(() => {
            this.confirmDelete(params)
          })
        }
      })
    },

    confirmDelete(params) {
      ProjectManage.statusDel(params).then((res) => {
        if(res.success) {
          this.getStatusList()
          this.$message.success(this.$t('common.base.tip.deleteSuccess'));
        } else {
          this.$message.error(res.message || this.$t('common.base.tip.deleteFail'));
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@src/modules/setting/projectManage/common/setCommon.scss';
.project-setting {
  .status-desc {
    font-size: 14px;
    height: 40px;
    line-height: 40px;
    color: #555555;
  }

}
</style>